package org.spring.springcaptcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.spring.springcaptcha.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static long VILID_MILLIS_TIME = 5*60*1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void genCaptcha(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession();

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        String code = lineCaptcha.getCode();
        try {
            response.setContentType("image/jpeg");
            response.setHeader("Pragma","No-cache");
            lineCaptcha.write(response.getOutputStream());
            System.out.println(code);
            //写入到session
            session.setAttribute(captchaProperties.getSession().getCode(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
            response.getOutputStream().close();
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session){
        System.out.println("用户输入验证码："+captcha);
        if(!StringUtils.hasLength(captcha)){
            return false;
        }

        //从session中获取
        String code = (String)session.getAttribute(captchaProperties.getSession().getCode());
        Long date = (Long)session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equalsIgnoreCase(code) && System.currentTimeMillis()-date < VILID_MILLIS_TIME){
            return true;
        }

        return false;
    }
}

